<template>
  <a-modal
    :visible="modelValue"
    :title="title"
    width="600px"
    :confirm-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="开户机构" name="acctInstitution">
        <a-select
          v-model:value="formData.acctInstitution"
          placeholder="请选择开户机构"
          :disabled="isEditMode"
          size="small"
        >
          <a-select-option v-for="option in institutionOptions" :key="option.value" :value="option.value">
            {{ option.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="账户分类" name="acctType">
        <a-select
          v-model:value="formData.acctType"
          placeholder="请选择账户分类"
          :disabled="isEditMode"
          size="small"
        >
          <a-select-option :value="1">产品账户</a-select-option>
          <a-select-option :value="2">TA账户</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="证书ID" name="certificateId">
        <a-input
          v-model:value="formData.certificateId"
          placeholder="请输入证书ID"
          :maxlength="150"
          size="small"
        />
      </a-form-item>

      <a-form-item label="备注" name="remark">
        <a-textarea
          v-model:value="formData.remark"
          placeholder="请输入备注"
          :rows="3"
          :maxlength="500"
          show-count
          size="small"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, watch } from 'vue'
import { FORM_RULES } from '../constants/index.js'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ''
  },
  loading: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({
      id: null,
      acctInstitution: '',
      acctType: null,
      certificateId: '',
      remark: ''
    })
  },
  institutionOptions: {
    type: Array,
    default: () => []
  },
  isEditMode: {
    type: Boolean,
    default: false
  }
})

// 表单验证规则
const rules = FORM_RULES

// Emits
const emit = defineEmits(['update:modelValue', 'ok', 'cancel'])

// Refs
const formRef = ref()

// Watchers
watch(() => props.modelValue, (newVal) => {
  if (!newVal) {
    // 弹窗关闭时重置表单
    formRef.value?.resetFields()
  }
})

// Methods
const handleOk = async () => {
  try {
    await formRef.value.validate()
    emit('ok')
  } catch (error) {
    // 验证失败，不关闭弹窗
    console.log('表单验证失败:', error)
  }
}

const handleCancel = () => {
  emit('cancel')
  emit('update:modelValue', false)
}

const handleVisibleChange = (visible) => {
  emit('update:modelValue', visible)
}

// 暴露表单引用给父组件
defineExpose({
  formRef
})
</script>